package cn.edu.hzvtc.haowen.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;


import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.edu.hzvtc.haowen.common.annotation.Log;
import cn.edu.hzvtc.haowen.common.core.controller.BaseController;
import cn.edu.hzvtc.haowen.common.core.domain.AjaxResult;
import cn.edu.hzvtc.haowen.common.enums.BusinessType;
import cn.edu.hzvtc.haowen.domain.WenjuanInfo;
import cn.edu.hzvtc.haowen.service.IWenjuanInfoService;
import cn.edu.hzvtc.haowen.common.utils.poi.ExcelUtil;
import cn.edu.hzvtc.haowen.common.core.page.TableDataInfo;



/**
 * 问卷信息Controller
 * 
 * @author haowen
 * @date 2024-05-02
 */
@RestController
@RequestMapping("/wenjuan/wenjuan_info")
public class WenjuanInfoController extends BaseController
{
    @Autowired
    private IWenjuanInfoService wenjuanInfoService;

    /**
     * 查询user未完成的问卷
     */
    @PreAuthorize("@ss.hasPermi('mine:wenjuan_mine:list_todo')")
    @GetMapping("/todo")
    public AjaxResult todo()
    {
        List<WenjuanInfo> list =
                wenjuanInfoService.selectWenjuanInfoUserTodo(
                        getDeptId().toString(),
                        Arrays.stream(getLoginUser().getUser().getDept().getAncestors().split(",")).toArray(String[]::new)
                        );
        return AjaxResult.success(list);
    }


    /**
     * 查询问卷信息列表
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_info:list')")
    @GetMapping("/list")
    public TableDataInfo list(WenjuanInfo wenjuanInfo)
    {
        startPage();
        List<WenjuanInfo> list = wenjuanInfoService.selectWenjuanInfoList(wenjuanInfo);
        return getDataTable(list);
    }

    /**
     * 导出问卷信息列表
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_info:export')")
    @Log(title = "问卷信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WenjuanInfo wenjuanInfo)
    {
        List<WenjuanInfo> list = wenjuanInfoService.selectWenjuanInfoList(wenjuanInfo);
        ExcelUtil<WenjuanInfo> util = new ExcelUtil<WenjuanInfo>(WenjuanInfo.class);
        util.exportExcel(response, list, "问卷信息数据");
    }

    /**
     * 获取问卷信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_info:query')")
    @GetMapping(value = "/{wenjuanId}")
    public AjaxResult getInfo(@PathVariable("wenjuanId") Integer wenjuanId)
    {
        return success(wenjuanInfoService.selectWenjuanInfoByWenjuanId(wenjuanId));
    }

    /**
     * 新增问卷信息
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_info:add')")
    @Log(title = "问卷信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WenjuanInfo wenjuanInfo)
    {
        wenjuanInfo.setCreateBy(getUsername());
        return toAjax(wenjuanInfoService.insertWenjuanInfo(wenjuanInfo));
    }

    /**
     * 修改问卷信息
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_info:edit')")
    @Log(title = "问卷信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WenjuanInfo wenjuanInfo)
    {
        wenjuanInfo.setUpdateBy(getUsername());
        return toAjax(wenjuanInfoService.updateWenjuanInfo(wenjuanInfo));
    }

    /**
     * 删除问卷信息
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_info:remove')")
    @Log(title = "问卷信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{wenjuanIds}")
    public AjaxResult remove(@PathVariable Integer[] wenjuanIds)
    {
        return toAjax(wenjuanInfoService.deleteWenjuanInfoByWenjuanIds(wenjuanIds));
    }

    /**
     * 查询问卷信息by uuid
     */
    // 不需要权限，需要通过判断问卷类型和密码

    // TODO UUID Password，集合到wenjuanInfo中，前端需修改
    @PostMapping(value = "/u/{uuid}")
    // 无需权限
    // 已在 src/main/java/cn/edu/hzvtc/haowen/framework/config/SecurityConfig.java 中配置 .antMatchers("/wenjuan/wenjuan_info/u/**").permitAll()
    //
    public AjaxResult getInfoByUuid(@RequestBody WenjuanInfo wenjuanInfo)
    {

        logger.debug("============== user getWenjuanInfoByUuid ================");

        String uuid = wenjuanInfo.getWenjuanUuid();
        String pwd = wenjuanInfo.getWenjuanPassword();
        WenjuanInfo wenjuan = wenjuanInfoService.selectWenjuanInfoByWenjuanUuid(uuid);
        if (checkUserAndType(wenjuan,pwd)){
            return success(wenjuan);
        }else {
            // 需要密码返回data:{type:2} ，部门要求返回data:{type:3}
            /*
            * 格式，{code: 200, msg: "操作成功", data:{type:2}}
            *
            * */
            return wenjuan.getWenjuanType().equals(WenjuanTypeToUser.PRIVATE.getType()) ?
                    success(
                            new HashMap<String, Integer>(){{ put("typeCode",202);}}
                    ) :
                    success(new HashMap<String, Integer>(){{put("typeCode",203);}}
                    );
        }
    }

    /**
     * 重要方法，判断用户是否有权限查看问卷
     * @param w 问卷WenjuanInfo
     * @param pwd 用户输入的密码
     * @return 是否有权限 true false
     */
    public Boolean checkUserAndType(WenjuanInfo w,String pwd)
    {
        String t = w.getWenjuanType();
        // 1 是公共问卷
        if (WenjuanTypeToUser.PUBLIC.getType().equals(t)){
            logger.info("the wenjuan is public, send it to user.");
            return true;
        }



        // 2 是私有问卷
        else if (WenjuanTypeToUser.PRIVATE.getType().equals(t)){
            // 如有没有密码
            if ("".equals(w.getWenjuanPassword())){
                logger.info("??? wenjuan has pwd, but the pwd is null, send wenjuan to user. Need Check ???");
                return true;
            }
            // 判断密码是否正确
            pwd = (pwd==null?"":pwd);

            if(pwd.equals(w.getWenjuanPassword())){
                logger.info("the password is correct, send wenjuan to user.");
                return true;
            }
        }



        // 3是内部问卷
        else if (WenjuanTypeToUser.DEPARTMENT.getType().equals(t)){

            // 首先判断 是否 存在 登录用户
            try {
                getLoginUser();
            }catch (Exception e){
                logger.info("anymous user want to get the wenjuan, refused.");
                return false;
            }


            // 判断当前用户是否是问卷下发的部门
            if(w.getCreateFor().equals(
                    (getDeptId()).toString()
            )){
                logger.info("the user under the department:"+getDeptId()+" of the wenjuan, send wenjuan to user.");
                return true;
            }


            // 如果问卷的部门是上级或祖籍部门，也可以查看
            else if (
                    Arrays.stream(getLoginUser().getUser().getDept().getAncestors().split(",")).anyMatch(s->s.equals(w.getCreateFor()))
                    ){
                logger.info("the user dept:"+getDeptId()+" is under wenjuan dept:"+w.getCreateFor()+" , send wenjuan to user.");
                return true;
            }

            else{
                logger.info("user has no permission to get the wenjuan, refused.");
                return false;
            }
        }

        logger.info("user has no permission to get the wenjuan, refused.");
        return false;
    }
}
